package com.syyo.gulimall.ware.config.rabbit;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @ author: wang
 * @ date: 2021/4/22 11:29
 * @ Description:
 */
@Configuration
public class MyMQConfig {


    public static final String STOCK_EXCHANGE = "stock-event-exchange";// 交换机
    public static final Integer EXPIRATION_TIME = 120000;//过期时间 单位毫秒

    public static final String STOCK_DELAY_QUEUE = "stock.delay.queue";// 延时队列
    public static final String STOCK_RELEASE_STOCK_QUEUE = "stock.release.stock.queue";// 释放队列

    public static final String STOCK_LOCKED_KEY = "stock.locked";//交换机和延迟队列绑定的key
    public static final String STOCK_RELEASE_KEY = "stock.release.key";//延迟队列的key
    public static final String STOCK_RELEASE = "stock.release.#";//交换机和释放队列绑定的key


    /**
     * 创建 死性队列
     *
     * @return
     */
    @Bean
    public Queue stockDelayQueue() {
        Map<String, Object> map = new HashMap<>();
        /*
         * x-dead-letter-exchange: order-event-exchange
         * x-dead-letter-routing-key: order.release.key
         * x-message-ttl: 60000
         */
        map.put("x-dead-letter-exchange", STOCK_EXCHANGE);
        map.put("x-dead-letter-routing-key", STOCK_RELEASE_KEY);
        map.put("x-message-ttl", EXPIRATION_TIME);
        Queue queue = new Queue(STOCK_DELAY_QUEUE, true, false, false, map);
        return queue;
    }

    /**
     * 释放队列
     *
     * @return
     */
    @Bean
    public Queue stockReleaseQueue() {
        Queue queue = new Queue(STOCK_RELEASE_STOCK_QUEUE, true, false, false);
        return queue;
    }

    /**
     * String name,交换机名称
     * boolean durable, 是否持久化
     * boolean autoDelete, 是否自动删除
     * Map<String, Object> arguments 扩展参数
     * 创建库存服务的交换机
     *
     * @return
     */
    @Bean
    public Exchange stockEventExchange() {

        return new TopicExchange(STOCK_EXCHANGE, true, false);
    }

    /**
     * 绑定延时队列
     * <p>
     * // String destination,目的地
     * // DestinationType destinationType, 目的地类型
     * // String exchange, 交换机
     * // String routingKey, 绑定key
     * // Map<String, Object> arguments 扩展参数
     */
    @Bean
    public Binding stockDelayOrderBinding() {
        return new Binding(STOCK_DELAY_QUEUE,
                Binding.DestinationType.QUEUE,
                STOCK_EXCHANGE,
                STOCK_LOCKED_KEY,
                null);
    }

    /**
     * 绑定释放队列
     *
     * @return
     */
    @Bean
    public Binding stockReleaseOrderBinding() {
        return new Binding(STOCK_RELEASE_STOCK_QUEUE,
                Binding.DestinationType.QUEUE,
                STOCK_EXCHANGE,
                STOCK_RELEASE,
                null);
    }
}
